const Routes = require('../utils/compile/route')

let Toast = require('../utils/compile/toast').default

function wrapFun(pre, wrapper) {
  return function () {
    try {
      wrapper && wrapper.apply(this, arguments)
    } finally{
      pre && pre.apply(this, arguments)
    }
  }
}

// https://regexr.com/4je5c
module.exports = function () {
  let ret = {
    initStaticRef(onLoad, refs, opt) {
      return wrapFun(onLoad, function (options) {
        const systemInfo = wx.getSystemInfoSync()

        this.$staticRefs = {}
        this.$systemInfo = systemInfo
        refs.forEach(v => {
          let k = v.trim().replace(/^(ref-)/, '')
          this.$staticRefs[k] = this.selectComponent('#' + v)
        })
        this.$getRef = function (refId) {
          return this.selectComponent('#ref-' + refId)
        }
        this.$native = {
          emit: this.triggerEvent.bind(this)
        }
        this.$rpx = function (v) {
          return v / 750 * systemInfo.windowWidth
        }
        this.$routePage = function(name, options) {
          let op = Object.assign({
            query: ''
          }, options)
          Routes.setRouteCache(this)
          let s = Routes.handlePageArgs(name, op.query)
          return this.$route(s, op)
        }
        this.$redirectPage = function(name, options) {
          let op = Object.assign({
            query: ''
          }, options)
          Routes.setRouteCache(this)
          let s = Routes.handlePageArgs(name, op.query)
          return this.$redirect(s, op)
        }
        this.$switchPage = function(name, options) {
          let op = Object.assign({
            query: ''
          }, options)
          Routes.setRouteCache(this)
          let s = Routes.handlePageArgs(name, op.query)
          return this.$switch(s, op)
        }
        this.$getRouteFrom = function () {
          return Routes.getRouteCache(this) || ''
        }
        this.$cusToast = function (message, options = {}) {
          Toast({
            duration: 3000,
            message: message,
            ...options
          });
        }
        this.$getPageIndex = function (pageName) {
          let pages = getCurrentPages()
          let ret = {
            index: -1,
            backLen: -1,
          }
          ret.index = pages.findIndex(page => page.$pageName === 'index')
          if (ret.index > -1) {
            ret.backLen = pages.length - ret.index - 1
          }
          return ret
        }
        if (opt.onLoad) {
          opt.onLoad(this, options)
        }
        // console.log('this', opt, refs)
      })
    }
  }
  return ret
}
